<template>
  <div ref="container" class="absolute inset-0 overflow-y-auto makeapie-box">
    <div
      class="float-left relative bg-white makeapie-box-viewer"
      v-for="image in data.images"
      :key="image.id"
    >
      <el-image :src="image.url" class="w-full"></el-image>
      <div class="absolute top-0 w-full h-full">
        <p>{{ image.name }}</p>
        <el-button @click="download(image.id)" class="absolute">
          下载模板
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import axios from "axios";

const container = ref(null);
const data = reactive({
  images: [],
});
let pieBox = null;
let list = null;

//下载模板
function download(id) {
  axios({
    method: "get",
    url: process.env.VUE_APP_TOMCAT + "/makeapie/pages/" + id + ".js",
  }).then((res) => {
    let url = window.URL.createObjectURL(
      new Blob([res.data], {
        type: "application/octet-stream",
      })
    );

    let link = document.createElement("a");
    link.download = id + ".js";
    link.href = url;
    link.click();
    URL.revokeObjectURL(url);
  });
}

//更新列表
function updateList(start, end) {
  for (let i = start; i < end; i++) {
    let errflag;
    let key;
    if (list[i].split("----").length > 1) {
      key = list[i].split("----");
      errflag = true;
    } else {
      key = list[i].split("---");
      errflag = false;
    }
    let id = errflag ? key[0] + "-" : key[0];
    data.images.push({
      id: id,
      name: key[1],
      url: process.env.VUE_APP_TOMCAT + "/makeapie/images/" + id + ".png",
    });
  }
}

onMounted(() => {
  pieBox = container.value;

  //获取清单
  axios({
    method: "get",
    url: process.env.VUE_APP_TOMCAT + "/makeapie/list.txt",
  }).then((res) => {
    if (res.status != 200) {
      return;
    }
    list = res.data.split("\r\n");
    updateList(0, 20);
  });

  //监听滚动
  let offsetHeight = pieBox.offsetHeight;
  pieBox.onscroll = () => {
    let scrollTop = pieBox.scrollTop;
    let scrollHeight = pieBox.scrollHeight;
    if (offsetHeight + scrollTop - scrollHeight >= -1) {
      updateList(data.images.length, data.images.length + 20);
    }
  };
});
</script>

<style lang="scss" scoped>
.makeapie-box {
  padding-bottom: 40px;

  div {
    border-radius: 5px;
  }

  .makeapie-box-viewer {
    width: 320px;
    height: 240px;
    margin-top: 40px;
    margin-left: 40px;

    div:nth-child(2) {
      opacity: 0;
      transition: 0.1s all ease-in-out;
      background: linear-gradient(
        180deg,
        rgba(255, 255, 255, 0.95) 0%,
        rgba(255, 255, 255, 0.88) 33%,
        rgba(255, 255, 255, 0.65) 100%
      );
    }

    div:nth-child(2):hover {
      opacity: 1;
    }

    p {
      width: 280px;
      font-size: 18px;
      margin-top: 20px;
      margin-left: 20px;
    }

    button {
      right: 20px;
      bottom: 20px;
      font-size: 14px;
    }
  }
}
</style>
